# -*- coding: utf-8 -*-
import uuid
import logging
import requests
import json
from datetime import datetime, timedelta
from urllib.parse import urlencode, parse_qs
from django.utils import timezone
from django.conf import settings
from django.core.cache import cache
import urllib3
from app.models import AmazonStore  # 修正导入路径
from app.intereface_amazon.amazon_config import SP_API_CREDENTIALS  # 修正导入路径

logger = logging.getLogger(__name__)

class EbayAuthService:
    EBAY_AUTH_URL = "https://auth.ebay.com/oauth2/authorize"
    EBAY_TOKEN_URL = "https://api.ebay.com/identity/v1/oauth2/token"
    EBAY_SANDBOX_AUTH_URL = "https://auth.sandbox.ebay.com/oauth2/authorize"
    EBAY_SANDBOX_TOKEN_URL = "https://api.sandbox.ebay.com/identity/v1/oauth2/token"

    EBAY_SCOPES = [
        'https://api.ebay.com/oauth/api_scope',
        'https://api.ebay.com/oauth/api_scope/sell.inventory',
        'https://api.ebay.com/oauth/api_scope/sell.marketing',
        'https://api.ebay.com/oauth/api_scope/sell.analytics.readonly',
        'https://api.ebay.com/oauth/api_scope/sell.finances',
        'https://api.ebay.com/oauth/api_scope/sell.fulfillment'
    ]

    def __init__(self, is_sandbox=False):
        self.is_sandbox = is_sandbox
        self.auth_url = self.EBAY_SANDBOX_AUTH_URL if is_sandbox else self.EBAY_AUTH_URL
        self.token_url = self.EBAY_SANDBOX_TOKEN_URL if is_sandbox else self.EBAY_TOKEN_URL
        self.client_id = settings.EBAY_CLIENT_ID
        self.client_secret = settings.EBAY_CLIENT_SECRET
        self.redirect_uri = settings.EBAY_REDIRECT_URI

    def get_auth_url(self, state):
        """生成eBay授权URL"""
        params = {
            'client_id': self.client_id,
            'response_type': 'code',
            'redirect_uri': self.redirect_uri,
            'scope': ' '.join(self.EBAY_SCOPES),
            'state': state
        }
        return f"{self.auth_url}?{urlencode(params)}"

    def get_access_token(self, code):
        """使用授权码获取访问令牌"""
        data = {
            'grant_type': 'authorization_code',
            'code': code,
            'redirect_uri': self.redirect_uri
        }
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        auth = (self.client_id, self.client_secret)

        try:
            response = requests.post(self.token_url, data=data, headers=headers, auth=auth)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            logging.error(f"获取eBay访问令牌失败: {str(e)}")
            raise

    def refresh_access_token(self, refresh_token):
        """刷新访问令牌"""
        data = {
            'grant_type': 'refresh_token',
            'refresh_token': refresh_token,
            'scope': ' '.join(self.EBAY_SCOPES)
        }
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        auth = (self.client_id, self.client_secret)

        try:
            response = requests.post(self.token_url, data=data, headers=headers, auth=auth)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            logging.error(f"刷新eBay访问令牌失败: {str(e)}")
            raise

    def get_seller_info(self, access_token, region='NA'):
        """
        获取卖家信息
        
        Args:
            access_token: 访问令牌
            region: 区域
            
        Returns:
            dict: 卖家信息
        """
        endpoint = self.SP_API_ENDPOINTS.get(region, self.SP_API_ENDPOINTS['NA'])
        url = f"{endpoint}/sellers/v1/marketplaceParticipations"
        
        headers = {
            'Authorization': f'Bearer {access_token}',
            'x-amz-access-token': access_token,
            'Content-Type': 'application/json',
            'User-Agent': 'YourAppName/1.0'
        }
        
        try:
            response = requests.get(url, headers=headers, timeout=30)
            response.raise_for_status()
            
            return response.json()
            
        except requests.exceptions.RequestException as e:
            logger.error(f"Failed to get seller info: {str(e)}")
            raise ValueError(f"Failed to get seller info: {str(e)}")
    
    def save_store_credentials(self, seller_id, credentials_data, user_id=None):
        """
        保存店铺认证信息
        
        Args:
            seller_id: 卖家ID
            credentials_data: 认证数据
            user_id: 用户ID
            
        Returns:
            AmazonStore: 店铺对象
        """
        try:
            # 查找或创建店铺记录
            store, created = AmazonStore.objects.get_or_create(
                seller_id=seller_id,
                defaults={
                    'store_name': f'Amazon Store {seller_id}',
                    'access_token': credentials_data['access_token'],
                    'refresh_token': credentials_data.get('refresh_token'),
                    'token_type': credentials_data.get('token_type', 'bearer'),
                    'expires_at': credentials_data['expires_at'],
                    'scope': credentials_data.get('scope', ''),
                    'is_active': True,
                    'user_id': user_id,
                }
            )
            
            # 如果店铺已存在，更新认证信息
            if not created:
                store.access_token = credentials_data['access_token']
                if credentials_data.get('refresh_token'):
                    store.refresh_token = credentials_data['refresh_token']
                store.token_type = credentials_data.get('token_type', 'bearer')
                store.expires_at = credentials_data['expires_at']
                store.scope = credentials_data.get('scope', '')
                store.is_active = True
                store.save()
            
            logger.info(f"Successfully saved credentials for seller: {seller_id}")
            return store
            
        except Exception as e:
            logger.error(f"Failed to save store credentials: {str(e)}")
            raise ValueError(f"Failed to save store credentials: {str(e)}")